package com.weiqiao.mall.service.impl;

import com.google.gson.Gson;
import com.mongodb.client.model.Filters;
import com.weiqiao.mall.domain.SpecificationsEntity;
import com.weiqiao.mall.repository.ISpecificationsRepository;
import com.weiqiao.mall.service.ISpecificationsService;
import com.weiqiao.utils.MallUtil;
import com.weiqiao.utils.PageUtil;
import com.weiqiao.utils.StringUtils;
import lombok.extern.log4j.Log4j;
import org.apache.commons.collections4.CollectionUtils;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.regex.Pattern;

/**
 * @Description: 宝贝规格Service实现类
 * @author: xujun
 * @Date: 2019/10/24 17:10
 */
@Log4j
@Service("specificationsService")
public class SpecificationsServiceImpl implements ISpecificationsService {

    @Autowired
    private ISpecificationsRepository specificationsRepository;

    /**
     * 保存宝贝规格
     *
     * @param request 请求数据
     * @return boolean 返回布尔类型
     */
    @Override
    public ResponseEntity saveSpecifications(HttpServletRequest request) {
        int companyId = MallUtil.getCompanyId(request);
        Map<String, Object> resultMap = new HashMap<>(2);
        if (companyId == 0) {
            resultMap.put("result", false);
            resultMap.put("msg", "公司id不存在，保存失败");
            return new ResponseEntity(resultMap, HttpStatus.OK);
        }
        Document document = new Document();
        document.append("specs_id", String.valueOf(System.currentTimeMillis()));
        document.append("company_id", companyId);
        add(request, document);
        boolean b = specificationsRepository.saveSpecifications(document);
        resultMap.put("result", b);
        resultMap.put("msg", b ? "保存成功" : "保存失败");
        return new ResponseEntity(resultMap, HttpStatus.OK);
    }

    /**
     * 统计宝贝规格总数
     *
     * @param filter 过滤条件
     * @return boolean 返回整型
     */
    @Override
    public int getSpecificationsCount(Bson filter) {
        return specificationsRepository.getSpecificationsCount(filter);
    }

    /**
     * 更新宝贝规格
     *
     * @param request 请求数据
     * @return boolean 布尔类型
     */
    @Override
    public ResponseEntity updateSpecifications(HttpServletRequest request) {
        String specs_id = MallUtil.getString(request,"specs_id","");
        //获取公司id
        int companyId = MallUtil.getCompanyId(request);
        Bson filter = Filters.eq("specs_id", specs_id);
        filter = Filters.and(filter, Filters.eq("company_id", companyId));
        //先查询是否存在
        String jsonByFilter = this.getSpecificationsJsonByFilter(filter);
        Map<String, Object> resultMap = new HashMap<>(2);
        if (StringUtils.isBlank(jsonByFilter)) {
            resultMap.put("result", false);
            resultMap.put("msg", "宝贝规格不存在或已被删除，更新失败");
            return new ResponseEntity(resultMap, HttpStatus.OK);
        }
        Document document = Document.parse(jsonByFilter);
        add(request, document);
        boolean b = specificationsRepository.updateSpecifications(filter, document, false);
        resultMap.put("result", b);
        resultMap.put("msg", b ? "更新成功" : "更新失败");
        return new ResponseEntity(resultMap, HttpStatus.OK);
    }

    /**
     * 新增和编辑入库公用方法
     *
     * @param request
     * @param document
     */
    private void add(HttpServletRequest request, Document document) {
        String name = MallUtil.getString(request,"name","");
        Integer sort = MallUtil.getInteger(request,"sort",1);
        String value = MallUtil.getString(request,"value","");
        String values = MallUtil.getString(request,"values","");
        document.append("name", name);
        document.append("sort", sort);
        List<String> list = new ArrayList<>();
        if (StringUtils.isNotBlank(value)) {
            list.add(value);
        }
        if (StringUtils.isNotBlank(values)) {
            String[] split = values.split(",");
            if (split != null && split.length > 0) {
                list.addAll(Arrays.asList(split));
            }
        }
        document.append("value", list);
    }

    /**
     * 根据条件获取单条宝贝规格数据
     *
     * @param filter 过滤条件
     * @return String json类型字符串
     */
    @Override
    public String getSpecificationsJsonByFilter(Bson filter) {
        return specificationsRepository.getSpecificationsJsonByFilter(filter);
    }

    /**
     * 删除宝贝规格
     *
     * @param specs_id 主键
     * @return boolean 返回布尔类型
     */
    @Override
    public ResponseEntity deleteSpecifications(String specs_id) {
        Bson filter = Filters.eq("specs_id", specs_id);
        String jsonByFilter = this.getSpecificationsJsonByFilter(filter);
        Map<String, Object> resultMap = new HashMap<>(2);
        if (StringUtils.isBlank(jsonByFilter)) {
            resultMap.put("result", false);
            resultMap.put("msg", "宝贝规格不存在或已被删除，删除失败");
            return new ResponseEntity(resultMap, HttpStatus.OK);
        }
        boolean b = specificationsRepository.deleteSpecifications(filter);
        resultMap.put("result", b);
        resultMap.put("msg", b ? "删除成功" : "删除失败");
        return new ResponseEntity(resultMap, HttpStatus.OK);
    }

    /**
     * 获取宝贝规格列表
     *
     * @param request  请求数据包
     * @param pageable 分页排序数据
     * @return Map 返回Map
     */
    @Override
    public Map getSpecsList(HttpServletRequest request, Pageable pageable) {
        //获取公司id
        int companyId = MallUtil.getCompanyId(request);
        //封装查询条件
        Bson filter = Filters.eq("company_id", companyId);
        String name = request.getParameter("name");
        if (StringUtils.isNotBlank(name)) {
            Pattern pattern = Pattern.compile("^.*" + name + ".*$", Pattern.CASE_INSENSITIVE);
            filter = Filters.and(filter, Filters.eq("name", pattern));
        }
        //查询数据
        List<String> specsList = specificationsRepository.getSpecsList(filter, pageable);
        List<Map> resultList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(specsList)) {
            Gson gson = new Gson();
            for (String str : specsList) {
                SpecificationsEntity specificationsEntity = gson.fromJson(str, SpecificationsEntity.class);
                Map map = new HashMap(5);
                map.put("specs_id", specificationsEntity.getSpecs_id());
                map.put("company_id", specificationsEntity.getCompany_id());
                map.put("name", specificationsEntity.getName());
                map.put("sort", specificationsEntity.getSort());
                map.put("value", StringUtils.join(specificationsEntity.getValue(), "、"));
                resultList.add(map);
            }
        }
        //获取总记录数
        int count = this.getSpecificationsCount(filter);
        return PageUtil.toPage(resultList, count);
    }

    @Override
    public List<SpecificationsEntity> getSpecificationsList(HttpServletRequest request) {
        //获取公司id
        int companyId = MallUtil.getCompanyId(request);
        //封装查询条件
        Bson filter = Filters.eq("company_id", companyId);
        //查询数据
        List<String> specsList = specificationsRepository.getList(filter);
        List<SpecificationsEntity> resultList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(specsList)) {
            Gson gson = new Gson();
            for (String str : specsList) {
                SpecificationsEntity specificationsEntity = gson.fromJson(str, SpecificationsEntity.class);
                resultList.add(specificationsEntity);
            }
        }
        return resultList;
    }
}
